<template>
  <div>
    <el-tree
      ref="treeRef"
      :data="treeData"
      show-checkbox
      node-key="id"
      :default-checked-keys="defaultCheckedKeys"
      :props="{
        children: 'children',
        label: 'label'
      }"
      height="400px"
    />
    <div class="dialog-footer">
      <el-button @click="emit('close')">取消</el-button>
      <el-button type="primary" @click="handleConfirm">确定</el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { api } from '@/utils/api'

const props = defineProps({
  project: {
    type: Object,
    required: true
  }
})

const emit = defineEmits(['close'])

const treeRef = ref(null)
const allSections = ref([])
const loading = ref(false)

// 获取所有模板章节
const fetchAllSections = async () => {
  try {
    loading.value = true
    const response = await api.sections.listAll()
    allSections.value = response.data || []
    console.log('获取到的模板章节:', allSections.value.length, '个')
  } catch (error) {
    console.error('获取章节列表失败:', error)
    allSections.value = []
  } finally {
    loading.value = false
  }
}

// 构造树形数据：章节 → 表单
const treeData = computed(() => {
  let data = allSections.value.map(sec => ({
    id: `section_${sec._id}`,
    label: sec.name,
    children: (sec.forms || []).map(f => ({
      id: `form_${f._id}`,
      label: f.name
    }))
  }))
  console.log(data,'data')
  return data
})

// 默认勾选
const defaultCheckedKeys = computed(() => {
  if (!props.project.configSections) return []
  const keys = []
  props.project.configSections.forEach(sectionConfig => {
    // 处理新的数据结构：sectionId 可能是字符串ID，也可能是被populate的对象
    let sectionId
    if (typeof sectionConfig.sectionId === 'object' && sectionConfig.sectionId._id) {
      // 被populate的情况
      sectionId = sectionConfig.sectionId._id
    } else if (typeof sectionConfig.sectionId === 'string') {
      // 字符串ID的情况
      sectionId = sectionConfig.sectionId
    } else {
      // 旧格式，直接是sectionId
      sectionId = sectionConfig
    }
    
    keys.push(`section_${sectionId}`)
    
    // 找到对应的章节，然后添加其表单
    let section
    if (typeof sectionConfig.sectionId === 'object' && sectionConfig.sectionId._id) {
      // 如果已经被populate，直接使用
      section = sectionConfig.sectionId
    } else {
      // 否则从allSections中查找
      section = allSections.value.find(s => s._id === sectionId)
    }
    
    if (section && section.forms) {
      section.forms.forEach(f => keys.push(`form_${f._id}`))
    }
  })
  return keys
})

// 根据表单ID获取完整的表单数据
const getCompleteFormData = (formId) => {
  // 首先从 formStore 中查找
  const formFromStore = formStore.forms.find(f => f.id === formId)
  if (formFromStore) {
    return { ...formFromStore }
  }
  
  // 如果 formStore 中没有，从 sectionsStore 中查找
  let foundForm = null
  sectionsStore.sections.forEach(sec => {
    if (sec.forms) {
      const form = sec.forms.find(f => f.id === formId)
      if (form) {
        foundForm = form
      }
    }
  })
  
  return foundForm ? { ...foundForm } : null
}

const handleConfirm = () => {
  const checkedKeys = treeRef.value.getCheckedKeys()
  const configSections = []

  checkedKeys.forEach((key, index) => {
    if (key.startsWith('section_')) {
      const secId = key.split('_')[1]
      // 验证章节存在
      const sec = allSections.value.find(s => s._id === secId)
      if (sec) {
        configSections.push({
          sectionId: secId,
          order: index + 1, // 基于选择顺序设置order
          config: {} // 默认为空配置，可以后续扩展
        })
      }
    }
  })
  
  console.log('配置的章节:', configSections)
  emit('close', configSections)
}

// 组件挂载时获取数据
onMounted(() => {
  fetchAllSections()
})
</script>

<style scoped>
.dialog-footer {
  margin-top: 16px;
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style> 